package com.zhao.task.utils;

import com.google.common.collect.Maps;
import com.zhao.task.config.TaskConfig;
import com.zhao.task.config.TaskConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.context.properties.bind.Bindable;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.core.env.Environment;

import java.util.HashMap;
import java.util.Map;

/**
 * 解析轮询配置信息
 *
 * @author zhao
 * @date 2018-11-04
 */
@Slf4j
public class TaskProperty {

    /**
     * 轮询配置MAP,key为轮询服务名
     */
    private Map<String, TaskConfig> taskConfigMap = Maps.newHashMap();

    public Map<String, TaskConfig> getTaskConfigMap() {
        return taskConfigMap;
    }

    /**
     * 初始化赋值
     *
     * @param environment SpringBoot Environment
     * @return
     */
    public TaskProperty(Environment environment) {
        Map<String, TaskConfig> map = getTaskConfig(environment);
        if (map == null || map.isEmpty()) {
            log.error("初始化轮询配置失败");
            return;
        }
        this.taskConfigMap = map;
    }

    /**
     * 获取轮询配置
     *
     * @param environment SpringBoot Environment
     * @return
     */
    public static Map<String, TaskConfig> getTaskConfig(Environment environment) {
        String keys = environment.getProperty(TaskConstant.TASK_KEYS_PATH);
        if (StringUtils.isBlank(keys)) {
            log.error("{}未配置。", TaskConstant.TASK_KEYS_PATH);
            return null;
        }
        Binder binder = Binder.get(environment);

        Map<String, TaskConfig> map = new HashMap<>();
        for (String key : keys.split(",")) {
            TaskConfig item = binder.bind(TaskConstant.TASK_CONFIG_PATH + "." + key, Bindable.of(TaskConfig.class)).get();
            item.setKey(key);
            map.put(key, item);
        }
        return map;
    }


}

